package gitee.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import gitee.controller.dto.AuthInfo;
import gitee.controller.dto.AuthSuccess;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.Map;

/**
 * 登录用 gitee.controller
 *
 * @author Lee
 * @date 2021/4/24 17:30
 */
@RestController
public class LoginController {


    @Autowired
    private RestTemplate restTemplate;

    /**
     * 授权页面引导
     *
     * @return ModelAndView
     */
    @RequestMapping("/login")
    public ModelAndView initLogin() {
        ModelAndView view = new ModelAndView();
        view.addObject("href",
                "https://gitee.com/oauth/authorize?client_id=bf77398546eb40e69dbe95d566055952d7d29637043cd8ecdf21ab8b27d49f88&redirect_uri=http://localhost:8080/oauth/redirectUri&response_type=code");
        view.setViewName("login");
        return view;
    }

    /**
     * 获取授权后 的 令牌获取
     *
     * @param code
     * @return
     * @throws JsonProcessingException
     */
    @RequestMapping("/oauth/redirectUri")
    public String redirectUri(String code) throws JsonProcessingException {
        HttpHeaders headers = new HttpHeaders();
        //如果发送的参数数据是json数据的话，需要添加如下特殊的请求头
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        MultiValueMap param = new LinkedMultiValueMap();
        param.add("grant_type", "authorization_code");
        param.add("code", code);
        param.add("client_id", "bf77398546eb40e69dbe95d566055952d7d29637043cd8ecdf21ab8b27d49f88");
        param.add("redirect_uri", "http://localhost:8080/oauth/redirectUri");
        param.add("client_secret", "e1d46716538e9229a084c691045ad673d60dee7869aaa0e42215fda4f21dea9e");
        HttpEntity requestBody = new HttpEntity(param, headers);


        String url = "https://gitee.com/oauth/token";
        ResponseEntity<AuthSuccess> entity = restTemplate.postForEntity(url, requestBody, AuthSuccess.class);
        return "ok";
    }
}
